package cn.dao;

import cn.db.DBConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库的CURD基本操作
 * @author yale
 * @create 2017/10/9
 * @version 0.1
 */
public class BaseDao {
    /**
     * 基本查询
     */
    public ResultSet findAll(String sql, String params[]){
        ResultSet rSet = null;

        Connection con = DBConnection.getCon();

        try{
            //System.out.println(sql);
            //System.out.println(params[0]);   如果没有传入参数,则此处打印日志将会报错
            PreparedStatement pst = con.prepareStatement(sql);
            if(null!=params){
                for (int i = 0; i < params.length; i++){
                    pst.setString(i+1, params[i]);
                }
            }
            rSet = pst.executeQuery();
        } catch (SQLException e){
            e.printStackTrace();
        }
        return rSet;
    }
    /**
     * 基本数据库操作   增删改查
     */
    public int op(String sql, String params[]){
        int n = -1;
        Connection con = DBConnection.getCon();
        PreparedStatement pst = null;
        try {
            pst = con.prepareStatement(sql);
            if (null != params) {
                for (int i = 0; i < params.length; i++) {
                    pst.setString(i+1, params[i]);
                }
            }
            n = pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return n;
    }
    /**
     * 关闭连接
     */
    public void close(){
        DBConnection.closeAll();
    }
}
